#include "utils.h"
#include <string.h>


bool iscodefile( char *filename )
{
    char * suffix = NULL; 
    if( (suffix = strrchr( filename, '.' )) == NULL )
    {
        return false;
    }

    if( strcmp( suffix, ".h") == 0 
        || strcmp( suffix, ".c") == 0 
        || strcmp( suffix, ".cpp") == 0 
        || strcmp( suffix, ".hpp") == 0 
        || strcmp( suffix, ".cc") == 0 )
    {
        return true;
    }
    return false;

}


bool iswhitespace( char chr )
{
    if( chr == '\t' || chr == ' ' || chr == '\r' || chr == '\n' )
    {
        return true;
    }
    return false;
}

bool isoperator( char chr )
{
    if( strchr("{}[]<>+-*/&|,;#!=", chr) )
    {
        return true;
    }
    return false;
}

bool isendwithbrace( char *str )
{
    size_t len = strlen( str );
    if( len > 1 && strchr( "{}", str[ len - 1 ]))
        return true;
    return false;
}


void str_rm_extra_wsp( char *str , char *simplify_line )
{
    unsigned int i = 0;
    char *p = str;
    //whitespace at the beginning is already moved
    simplify_line[i++] = *p++;
    do
    {
        // multiple whitespace considered as one
        if( iswhitespace( *p ))
        {
            if( simplify_line[i - 1] != ' ' && !isoperator( simplify_line[ i - 1 ]))
            {
                simplify_line[i++] = ' ';
            }
        }
        // remove whitespace around operator 
        else if( isoperator( *p ))
        {
            if( simplify_line[i - 1] == ' ' )
            {
                simplify_line[i - 1] = *p;
            }
            else
            {
                simplify_line[i++] = *p;
            }
        }
        else
        {
            simplify_line[i++] = *p;
        }
    } while( *(++p));

    /* remove trailing whitespace */
    if( simplify_line[i - 1] == ' ' )
        simplify_line[i - 1] = '\0';
    else
        simplify_line[i] = '\0';

    return;

}

bool iscomments( char *str, bool *multiple_line )
{
    char *p = str;

    if( *multiple_line )
    {
        if( strstr( p, "*/"))
            *multiple_line = false;
        return true;
    }

    if( strncmp( p, "//", 2 ) == 0 )
    {
        //single-line comment
        return true;
    }

    if( strncmp( p, "/*", 2 ) == 0 )
    {
        if( strstr( p, "*/") != NULL )
        {
            //multi-line comment 
            return true;
        }
        else
        {
            //multi-line comment
            *multiple_line = true;
            return true;
        }
    }
    return false;
    
}
